#!/bin/sh
#author:scl
#write by 2017-04-22

#百战沙城H5

#定义参数
ssh='ssh -A -o StrictHostKeyChecking=no -p 22'
mysqldump='/usr/local/mysql/bin/mysqldump -uroot -p`cat /data/save/mysql_root`'
mysql="/usr/local/mysql/bin/mysql -uroot -p`cat /data/save/mysql_root`"
sshmysql='/usr/local/mysql/bin/mysql -uroot -p`cat /data/save/mysql_root`'
scp='scp -l 3000 -r -o StrictHostKeyChecking=no '
gamedir="/data/workspace/yishouh5/"
#定义域名解析IP的机器和目录
yw_center=119.29.132.172
Domain_ip=119.29.108.100
Domain_dir="/data/bzsc_script"
data=`date +%Y-%m-%d`

#更新ip
stable_ip=123.207.226.14                #定义源ip
nowtime=`date +%Y-%m-%d_%H-%M`  
src_agent_id="dev_s1"                   #定义从哪里拉取
stable_dir="/data/workspace/"           #定义目录路径
gamedir="/data/workspace/yishouh5/"       #定义目录路径
dir="/data/update_bzsch5/"

#初始化文件(进度条)
cat /dev/null > ./develop.log

if [ -n $1 ];then
    if [ $1 == "stop_game" -o $1 == "start_game" -o $1 == "Hot_update" -o $1 == "plush_file"  -o $1 == "game_update" ];then
            echo "yes" > ./implement.log
    else
            echo "no" > ./implement.log
    fi
fi

#功能目录：
function menu {
	echo -e "\r \033[32m \t\t\t\t\t使用菜单
	1、game_install 源IP 源SAgent_Id 目标IP 新装服Agent_Id 开服日期 如:2016-05-07 时间 如:10:30:00 [cross] 跨服参数 如果是跨服就传
	2、add_center Agent Id 域名 ip 端口 (添加服到中央后台)
	3、truncate_game 目标IP 渠道_ID 日期 时间  (清档)
	4、plush_file 用法: sh menu.sh plush_file gatfile.sh(列表) #上传更新文件
	5、Hot_update 用法: sh menu.sh Hot_update gatfile.sh(列表) #热更操作
	6、stop_game 用法: sh menu.sh stop_game gatfile.sh(列表)   #关游戏
	7、game_update 用法: sh menu.sh game_update gatfile.sh(列表)   #更新游戏
	8、check_game 用法: sh menu.sh check_game gatfile.sh(列表) #检查游戏是否关闭
	9、start_game 用法: sh menu.sh start_game gatfile.sh(列表) #开游戏\033[0m"
}

#把服插入到中央后台
function add_center {
	#$1 为agent $2为id $3为domain $4为ip $5为端口
	id=`echo $2 |sed 's/s//g'`
	if [ "$1" == "test" ];then
		center=123.207.226.14
	else
		center=123.207.66.57
	fi
	type=2
	if [ "$1" == "cross" ];then
		type=3
	fi
	centerdb="bzsch5_center"
	datetime=`date +%s`
	result=`${ssh} $center "${sshmysql} ${centerdb} -e \"select * from s_plat_server where platform='$1' and plat_server=$id;\"| grep -v 'chinese_name'|wc -l"`
	if [ $result -ge 1 ];then
		echo -e "\033[33m ${Agent}_${Id}服务器列表已存在 添加失败 \033[0m"
	else
		echo -e "\033[32m ${Agent}_${Id}服务器列表正在添加 \033[0m"
	isql="${ssh} $center \"${sshmysql} ${centerdb} -e \"INSERT INTO s_plat_server (platform,plat_server,domain,ip,port,create_time,type) VALUES (\"$1\",\"$id\",\"$3\",\"$4\",\"$5\",\"$datetime\",$type)\"\""
	${ssh} $center "${sshmysql} ${centerdb} -e \"INSERT INTO s_plat_server (platform,plat_server,domain,ip,port,create_time,type) VALUES ('$1','$id','$3','$4','$5','$datetime',$type)\""
	[ $? -eq 0 ] && echo -e "\033[32m 服务器列表插入成功 \033[0m" || echo -e "\033[31m 服务器列表插入失败 \033[0m" && echo -e "\033[33m 重新执行:$isql \033[0m"
        ${ssh} $center "${sshmysql} ${centerdb} -e \"update s_open_server set install_time = '$8' where platform = '$1' and plat_server = '$id';\""
        [ $? -eq 0 ] && echo -e "\033[32m 服务器开服时间修改成功 \033[0m" || echo -e "\033[31m 服务器开服时间修改失败 \033[0m"
	fi
	#$ssh $yw_center "$sshmysql op_center -e \"insert into ywproject_bzsc_game_list(game_agent,server_id,public_ip,port,domian,qingdang,open_state,open_time,sys_ver,sampling_time) values('$1',$id,'$4','$5','$3',1,1,'$6',1,'2016-10-21 17:37:00')\""
	#$ssh $yw_center "$sshmysql op_center -e \"update ywproject_bzsc_open_server set open_status=1 where game_name='${1}_s${id}'\""

}



#游戏安装
function game_install {
	#初始化参数
	gamedir="/data/workspace/bzsch5/"
	#定义拉取服信息
	Sip=$1  					 #定义拉取数据IP
	SAgent_Id=$2 					 #定义拉取数据的服
	SAgent=`echo $2|awk -F'_' '{print $1}'` 	 #定义源服的渠道
	SId=`echo $2|awk -F'_' '{print $2}'`    	 #定义源服的ID
	Scrond="/etc/cron.d/bzsch5_${SAgent}_${SId}" 	 #定义源服计划任务
	Sgamedb="bzsch5_${SAgent_Id}"			 #定义源服主库数据库名称
	Sadmindb="bzsch5_${SAgent}_admin_${SId}"		 #定义源服admin数据库名称
	Sg=`echo $SId|sed 's/s/g/g'`
	Sngdir="/usr/local/nginx/conf/vhost/${Sg}.${SAgent}.bzsch5.conf"
	Sngdir1="/usr/local/nginx/conf/vhost/${SId}.${SAgent}.bzsch5.conf"

	#定义安装服信息
	ip=$3
	Agent=`echo $4|awk -F'_' '{print $1}'`	 	 #定义安装服务器的渠道
	Id=`echo $4|awk -F'_' '{print $2}'`		 #定义安装服务器的ID
	gamedb="bzsch5_${Agent}_${Id}"			 #定义安装主库数据库名称
	admindb="bzsch5_${Agent}_admin_${Id}"		 #定义安装admin数据库名称
	crond="/etc/cron.d/${gamedb}"			 #定义源服计划任务文件
    opentime="$5 $6"
	strftime_o=`date -d "$opentime" +%s`
	nip=`ifconfig | grep "inet addr:" | awk -F':|[ ]+' '{print $4}' | grep -v "127.0.0.1"` #获取内网IP
	id=`echo $Id |sed 's/s//g'`
	sg=`echo $Id|sed 's/s/g/g'`
	Sg=`echo $Id|sed 's/s/S/g'`
	sngdir="/usr/local/nginx/conf/vhost/${sg}.${Agent}.bzsch5.conf"
	sngdir1="/usr/local/nginx/conf/vhost/${Id}.${Agent}.bzsch5.conf"


	#检查参数是否为空
	[ $# -ge 5 ] || (echo -e "\033[31m 参数设置错误 \033[0m" && /bin/false)|| exit 1
        resultIP=`echo $1 |egrep [0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}`
        resultip=`echo $3 |egrep [0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}`
        if [ -z $resultIP ] || [ -z $resultip ];then
                echo -e "\033[31m IP格式不对 请重新输入 \033[0m" && exit 1
        fi
	mkdir -p /data/workspace/bzsch5/

    #检测装服ip是否内网或者同机
    #判断是否同台服务器
    Nip=`$ssh $Sip "ifconfig eth0|grep 'inet addr'|awk -F':' '{print \\$2}'| awk '{print \\$1}'"`
    $ssh $Nip "ls" >/dev/null
    result=$?
    if [ ${Sip} == ${ip} ];then
        Sip=127.0.0.1
         echo "${1}的内网ip是127.0.0.1"
    elif [ $result -eq 0 -a -n $Nip ];then
        Sip=$Nip
        echo "${1}的内网ip是${Nip}"
    else
        echo "${1}只能通过外网"
    fi

	#检测游戏是否存在
	if [ -d ${gamedir}${Agent}_${Id} ];then
		echo -e "\033[31m ${Agent}_${Id},已经存在，请检查! \033[0m"
		exit 1
	else
		result=`$ssh $Sip "ls -d ${gamedir}${SAgent_Id} |wc -l"`
		if [ $result -eq 0 ];then
			echo -e "\033[31m 原服务器:$SAgent_Id 不存在，请检查! \033[0m"
			exit 2
		fi
	fi

        #判断目标服和拉取服一致不
        if [ "$SAgent" == "$Agent" ];then
                echo -e "\033[32m 目标服平台和安装服平台一致 \033[0m"
	elif [ "$7" == 'Y' ];then
                echo -e "\033[32m 继续安装 \033[0m"
        else
                echo -e "\033[33m 目标服平台和安装服平台不一致 \033[0m"
                read -p "你确定要安装?(Yy|Nn)" result
                if [ "$result" == "Y" -o "$result" == "y" ];then
                        echo -e "\033[32m 继续安装 \033[0m"
                else
                        echo -e "\033[33m 脚本退出 \033[0m"
                        exit 1
                fi
        fi

	#检查拉区服的传统服还是激战版
#	V=`$ssh $Sip "$sshmysql ${Sgamedb} -e 'select value from sys_var where name = \"code_version\";'"|grep -v value`
#	if [ "$V" == "normal" ];then
#		echo -e "\033[31m 拉取服版本不正确 拉了传统版 \033[0m"
#		exit 1
#	elif [ "$V" == "fighting" ];then
#		echo -e "\033[32m 目标服是激战版 \033[0m"
#		sleep 5
#	else
#		echo -e "\033[32m 所在服版本不确认 \033[0m"
#		exit 1
#	fi

	#检查和导出数据库结构
	$ssh $Sip "mkdir -p /tmp/install_db"
	result=`$ssh $Sip ls /tmp/install_db/${Sgamedb}.sql|wc -l`
	adminresult=`$ssh $Sip ls /tmp/install_db/${Sadmindb}.sql|wc -l`

	if [ $result -eq 0 -o $adminresult -eq 0 ] ;then
		echo -e "\033[33m ${Sgamedb}.sql 不存在，正在导出! \033[0m"
		$ssh $Sip "$mysqldump -d ${Sgamedb} > /tmp/install_db/${Sgamedb}.sql" &> /dev/null
		$ssh $Sip "$mysqldump -d ${Sadmindb} > /tmp/install_db/${Sadmindb}.sql" &> /dev/null
		$ssh $Sip "$mysqldump -t ${Sgamedb} sys_var svr_ban > /tmp/install_db/version_${Sgamedb}.sql" &> /dev/null
		$ssh $Sip "$sshmysql ${Sadmindb} -e 'show tables;'|grep -vE 'g_login_log|g_operation_log'|egrep \"^g_\"|xargs $mysqldump -t ${Sadmindb} > /tmp/install_db/g_${Sadmindb}.sql" &> /dev/null
	else
		echo -e "\033[33m ${Sgamedb}.sql 已经存在 \033[0m"
		dirtime=`$ssh $Sip "ls -l /tmp/install_db/${Sgamedb}.sql| awk '{print \\$6\" \"\\$7}';"`
		today=`date | awk '{print $2" "$3}'`
		if [ "$today" != "$dirtime" ];then
			echo -e "\033[33m sql日期对不上，正在重新倒数据库 \033[0m"
			$ssh $Sip "$mysqldump -d ${Sgamedb} > /tmp/install_db/${Sgamedb}.sql" &> /dev/null
		        $ssh $Sip "$sshmysql ${Sadmindb} -e 'show tables;'|egrep \"^g_\"|xargs $mysqldump -t ${Sadmindb} > /tmp/install_db/g_${Sadmindb}.sql" &> /dev/null
			$ssh $Sip "$mysqldump -d ${Sadmindb} > /tmp/install_db/${Sadmindb}.sql" &> /dev/null
			$ssh $Sip "$mysqldump -t ${Sgamedb} sys_var svr_ban > /tmp/install_db/version_${Sgamedb}.sql" &> /dev/null
		fi
	fi

	#拉取计划任务
	$ssh  ${ip} " mkdir /tmp/install_db/ -p"
	$scp ${Sip}:${Scrond} ${crond} 
	[ $? -eq 0 ] && echo -e "\033[32m ${Agent}_${Id} 拉取计划任务成功! \033[0m" || (echo -e "\033[31m ${Agent}_${Id} 拉取计划任务失败! \033[0m"&& /bin/false) || exit 1
	
	#打包游戏目录
        $ssh ${Sip} "cd ${gamedir}${SAgent_Id}/ && tar  --exclude=.log  -zcf /tmp/install_db/${SAgent_Id}.tar.gz ."
        [ $? -eq 0 ] && echo -e "\033[32m ${Agent}_${Id} 游戏目录打包成功! \033[0m" || (echo -e "\033[31m ${Agent}_${Id} 游戏目录打包失败! \033[0m"&& /bin/false) || exit 1
	
	#发送游戏目录和sql
	rsync -az -e "ssh -o StrictHostKeyChecking=no" ${Sip}:/tmp/install_db/{g_${Sadmindb}.sql,${Sgamedb}.sql,${Sadmindb}.sql,version_${Sgamedb}.sql,${SAgent_Id}.tar.gz} /tmp/install_db/
	[ $? -eq 0 ] && echo -e "\033[32m ${Agent}_${Id} 文件拉取成功! \033[0m" || (echo -e "\033[31m ${Agent}_${Id} 文件拉取失败! \033[0m"&& /bin/false) || exit 1

	#解压游戏目录
        $ssh ${ip} "mkdir ${gamedir}${Agent}_${Id} && tar -zxf /tmp/install_db/${SAgent_Id}.tar.gz -C ${gamedir}${Agent}_${Id}"
	[ $? -eq 0 ] && echo -e "\033[32m ${Agent}_${Id} 解压文件成功! \033[0m" || (echo -e "\033[31m ${Agent}_${Id} 解压文件失败! \033[0m"&& /bin/false) || exit 1
	
	#拉取nginx
        $scp ${Sip}:${Sngdir1} ${sngdir1} 
        [ $? -eq 0 ] && echo -e "\033[32m ${Agent}_${Id} nginx配置文件拉取成功! \033[0m" || (echo -e "\033[31m ${Agent}_${Id} nginx配置拉取失败! \033[0m"&& /bin/false) || exit 1


	#修改数据库列表增长ID
	autoid=1
	autoid1=`expr ${id} - 1`
	autoid1=`expr $autoid1 % 2000`
	autoid1=`echo "$autoid1 * 1000000 +1"|bc`

	sed -i "s/AUTO_INCREMENT=[0-9]\+/AUTO_INCREMENT=${autoid1}/g" /tmp/install_db/${Sgamedb}.sql
	[ $? -eq 0 ] && echo -e "\033[32m 修改自增ID成功 \033[0m" ||  echo -e "\033[31m 修改自增ID失败 \033[0m"

	sed -i "s/AUTO_INCREMENT=[0-9]\+//g" /tmp/install_db/${Sadmindb}.sql
	[ $? -eq 0 ] && echo -e "\033[32m admin删除自增ID成功 \033[0m" ||  echo -e "\033[31m admin删除自增ID失败 \033[0m"
	
	
	#创建数据库
	which pv &> /dev/null
	[ $? -eq 0 ] || (echo -e "\033[33m 还没pv现在安装\033[0m";yum install pv -y)

	$mysql -e "set names utf8;create database ${gamedb}"
	[ $? -eq 0 ] && echo -e "\033[32m 数据库${gamedb}创建成功 \033[0m" || (echo -e "\033[31m 数据库${gamedb}创建失败 \033[0m" && /bin/false) || exit 1

	$mysql -e "set names utf8;create database ${admindb}"
	[ $? -eq 0 ] && echo -e "\033[32m 数据库${admindb}创建成功 \033[0m" || (echo -e "\033[31m 数据库${admindb}创建失败 \033[0m" && /bin/false) || exit 1

	#导入数据
	pv /tmp/install_db/${Sgamedb}.sql | $mysql ${gamedb}
	[ $? -eq 0 ] && echo -e "\033[32m ${gamedb}数据库结构导入成功 \033[0m" || (echo -e "\033[31m ${gamedb}数据库导入失败 \033[0m" && /bin/false) || exit 1

	pv /tmp/install_db/version_${Sgamedb}.sql | $mysql ${gamedb}
	[ $? -eq 0 ] && echo -e "\033[32m ${gamedb}version导入成功 \033[0m" || (echo -e "\033[31m ${gamedb}version导入失败 \033[0m" && /bin/false) || exit 1

	pv /tmp/install_db/${Sadmindb}.sql | $mysql ${admindb}
	[ $? -eq 0 ] && echo -e "\033[32m ${admindb}数据库结构导入成功 \033[0m" || (echo -e "\033[31m ${admindb}数据库导入失败 \033[0m" && /bin/false) || exit 1

    pv /tmp/install_db/g_${Sadmindb}.sql | $mysql ${admindb}
    [ $? -eq 0 ] && echo -e "\033[32m ${admindb}g表数据导入成功 \033[0m" || (echo -e "\033[31m ${admindb}g表数据导入失败 \033[0m" && /bin/false) || exit 1

	#删除主库log自增ID 
	$mysql ${gamedb} -e "show tables" | egrep "^log_" | xargs /usr/local/mysql/bin/mysqldump -uroot -p`cat /data/save/mysql_root` -d ${gamedb} --table > /tmp/install_db/log_${gamedb}.sql

	sed -i "s/AUTO_INCREMENT=[0-9]\+//g" /tmp/install_db/log_${gamedb}.sql
        [ $? -eq 0 ] && echo -e "\033[32m 主库log开头表删除自增ID成功 \033[0m" ||  echo -e "\033[31m 主库log开头表删除自增ID失败 \033[0m"

	pv /tmp/install_db/log_${gamedb}.sql | $mysql ${gamedb}
	[ $? -eq 0 ] && echo -e "\033[32m 主库log开头表导入成功 \033[0m" ||  echo -e "\033[31m 主库log开头表导入失败 \033[0m"


    #修改计划任务
    sed -i "s#${SAgent_Id}#${Agent}_${Id}#g" $crond
    [ $? -eq 0 ] && echo -e "\033[32m 计划任务修改成功 \033[0m"|| echo -e "\033[31m 失败 \033[0m"
    
    #修改nginx文件
    sed -i "s/\(root \/data\/workspace\/bzsch5\/\)\(.*\)\(\/web;\)/\1${Agent}_${Id}\3/g" ${sngdir1}
    [ $? -eq 0 ] && echo -e "\033[32m nginx修改成功 \033[0m"|| echo -e "\033[31m nginx修改失败 \033[0m"
    sed -i "s/\(server_name \)\(.*\)/\1${Id}.${Agent}.bzsch5.9217web.com;/g" ${sngdir1}
    [ $? -eq 0 ] && echo -e "\033[32m 域名修改成功 \033[0m"|| echo -e "\033[31m 域名修改失败 \033[0m"

    #判断渠道修改域名
   # sed -i "s/\(server_name \)\(.*\)/\1${sg}.${Agent}.bzsch5.9217web.com;/g" ${sngdir}
   # [ $? -eq 0 ] && echo -e "\033[32m 域名修改成功 \033[0m"|| echo -e "\033[31m 域名修改失败 \033[0m" 


    #php文件授权
    chmod -R 777 $gamedir${Agent}_${Id}/web/Core/Lang
    [ $? -eq 0 ] && echo -e "\033[32m /web/Core/Lang 授权成功 \033[0m"|| echo -e "\033[31m /web/Core/Lang 授权失败 \033[0m"
    chmod -R 777 $gamedir${Agent}_${Id}/web/RunTime
    [ $? -eq 0 ] && echo -e "\033[32m /web/RunTime 授权成功 \033[0m"|| echo -e "\033[31m /web/RunTime 授权失败 \033[0m"

    #清空web文件
    find /data/workspace/bzsch5/${Agent}_${Id}/web/RunTime/ -type f | xargs rm -f
    [ $? -eq 0 ] && echo -e "\033[32m 清除RunTime成功 \033[0m"|| echo -e "\033[31m 清除RunTime失败 \033[0m"

    #清空日志文件
    rm /data/workspace/bzsch5/${Agent}_${Id}/server/logs/ -rf
    
    #修改sys.config
    sqlpass=`cat /data/save/mysql_root` #获取数据库密码
    dbname=$gamedb			    #获取数据库名字
    
    time=(`echo $opentime |sed 's/-/ /g'|sed 's/:/ /g'`)
    sed -i "s/\({open_date, \)\(.*\)/\1{${time[0]}, ${time[1]}, ${time[2]}}},/g" ${gamedir}${Agent}_${Id}/server/config/sys.config
    [ $? -eq 0 ] && echo -e "\033[32m sys.config 开服时间修改成功 \033[0m"|| echo -e "\033[31m sys.config 开服时间修改失败 \033[0m"

    sed -i "s/\({pass, \)\(.*\)/\1\"${sqlpass}\"},/g" ${gamedir}${Agent}_${Id}/server/config/sys.config
    [ $? -eq 0 ] && echo -e "\033[32m sys.config 数据库密码修改成功 \033[0m"|| echo -e "\033[31m sys.config 数据库密码修改失败 \033[0m"

    sed -i "s/\({database, \)\(.*\)/\1\"$dbname\"},/g" ${gamedir}${Agent}_${Id}/server/config/sys.config
    [ $? -eq 0 ] && echo -e "\033[32m sys.config 数据库名字修改成功 \033[0m"|| echo -e "\033[31m sys.config 数据库名字修改失败 \033[0m"

    sed -i "s/\({platform, \)\(.*\)/\1\"${Agent}\"},/g" ${gamedir}${Agent}_${Id}/server/config/sys.config
    [ $? -eq 0 ] && echo -e "\033[32m sys.config 渠道修改成功 \033[0m"|| echo -e "\033[31m sys.config 渠道修改失败 \033[0m"
    
    sed -i "s/\({server_ids, \)\(.*\)/\1[${id}]},/g" ${gamedir}${Agent}_${Id}/server/config/sys.config
    [ $? -eq 0 ] && echo -e "\033[32m sys.config Id修改成功 \033[0m"|| echo -e "\033[31m sys.config Id修改失败 \033[0m"

    sed -i "s/\({gm, \)\(.*\)/\1 false},/g" ${gamedir}${Agent}_${Id}/server/config/sys.config
    [ $? -eq 0 ] && echo -e "\033[32m sys.config gm命令修改成功 \033[0m"|| echo -e "\033[31m sys.config gm命令修改失败 \033[0m"


    #获取游戏端口
    #maxport=`find -L ${gamedir} -name sys.config  | xargs grep "listen_port" | awk -F',|}|[ ]+' '{print $4}' | sort -n -r| head -1`
    useport=(`find -L ${gamedir} -name sys.config | xargs grep "listen_port" | awk -F',|}|[ ]+' 'BEGIN{ORS=" "}{print $4}'`)
    num=${#useport[*]}
        maxport=9001
        for (( i=0;i<$num;i++ ))
        do
            if [ $maxport -lt ${useport[$i]} ];then
                maxport=${useport[$i]}
            fi
        done
    #if [ -z $maxport ];then
    #	$i=9001
    #else
    #	let "gameport=maxport+1" 
    #fi
    gameport=$[$maxport+1]
    echo -e "\033[33m 本机已使用端口为${useport[@]} \033[0m"
    echo -e "\033[32m 端口为: $gameport \033[0m"

    #修改端口
    sed -i "s/{listen_port,.*/{listen_port, $gameport},/" ${gamedir}${Agent}_${Id}/server/config/sys.config
    [ $? -eq 0 ] && echo -e "\033[32m sys.config端口修改成功 修改为: $gameport \033[0m"|| echo -e "\033[31m sys.config端口修改失败,应修改为:  $gameport \033[0m"

     #修改head.sh
    sed -i "s/\(SERVER_NAME=\)\(.*\)/\1\"bzsch5_${Agent}_${Id}\"/g" ${gamedir}${Agent}_${Id}/server/script/head.sh
    [ $? -eq 0 ] && echo -e "\033[32m header.sh 项目名称修改成功 修改为:bzsch5_${Agent}_${Id}  \033[0m"|| echo -e "\033[31m header.sh 项目名称修改失败,应修改为: bzsch5_${Agent}_${Id} \033[0m"

    sed -i "s/\(IP=\)\(.*\)/\1\"$ip\"/g" ${gamedir}${Agent}_${Id}/server/script/head.sh
    [ $? -eq 0 ] && echo -e "\033[32m header.sh ip修改成功 修改为:$ip  \033[0m"|| echo -e "\033[31m header.sh ip修改失败,应修改为: $ip  \033[0m"


    #进行格式转换
    which dos2unix &> /dev/null
    [ $? -eq 1 ] && yum install dos2unix -y &> /dev/null
    dos2unix ${gamedir}${Agent}_${Id}/server/config/sys.config
    dos2unix ${gamedir}${Agent}_${Id}/server/script/head.sh

    #执行PHP脚本
    echo -e "\033[33m 正在执行php脚本 \033[0m"
    cd ${gamedir}${Agent}_${Id}/web/;
    /usr/local/php/bin/php index.php Content/SingleTask/Conf bzsch5 Single
    [ $? -eq 0 ] && echo -e "\033[32m php执行成功 \033[0m"|| (echo -e "\033[31m php执行失败 \033[0m" && echo -e "\033[31m 重新执行 php index.php Content/SingleTask/Conf bzsch5 Single \033[0m")

    #nginx重启
    /usr/local/nginx/sbin/nginx -s reload
    [ $? -eq 0 ] && echo -e "\033[32m nginx重启成功 \033[0m"|| echo -e "\033[31m nginx重启失败 \033[0m"

    #插入服务器列表
    add_center ${Agent} ${Id} ${Id}.${Agent}.bzsch5.9217web.com $ip $gameport $opentime $strftime_o
    echo "add_center ${Agent} ${Id} ${Id}.${Agent}.bzsch5.9217web.com $ip $gameport $opentime $strftime_o"


    #解析域名
    echo
    echo -e "\033[33m 正在解析域名\033[0m"
    $ssh $Domain_ip "cd $Domain_dir;python Domain_Action_Script.py -a $ip ${Id}.${Agent}.bzsch5.9217web.com"
    [ $? -eq 0 ] && echo -e "\033[32m ${sg}.${Agent}.bzsch5.9217web.com 域名解析成功\033[0m"


    #开启游戏
    cd  ${gamedir}${Agent}_${Id}/server/script;
    sh rel.sh start
    echo "${Agent}_${Id}装服时间${SECONDS}秒"
    exit 100
		
}



#清档

function truncate_game {
 
	#version user ip server date time
	$ssh ${yw_center} "/data/workspace/opcenter/shell/php_manage.py truncate ${1} ${2} ${3} ${4} ${5} ${6}"   
}

#修改游戏开服时间
function update_time
{
	$ssh $1 "cd ${gamedir}${2}/web/sh/ && /bin/sh restart_game.sh update_time 127.0.0.1 ${2} ${3} ${4}"
}

function look_log_content
{
	tail -200 ${1}
}

function plush_file {
        
        function gatfile {
		
        #创建目录
        $ssh $1 "mkdir -p $dir &&  find $dir -name 'bzsch5_server.tar.gz' -delete"
        [ $? -eq 0 ] && echo -e "\033[32m ${1} 目录创建成功 \033[0m" || echo -e "\033[33m ${1} 目录创建失败 \033[0m"

        #发送数据
        $scp $stable_ip:/tmp/update_bzsch5/$nowtime/bzsch5_server.tar.gz $1:$dir
        [ $? -eq 0 ] && echo -e "\033[32m ${1} 数据上传成功 \033[0m" || echo -e "\033[33m ${1} 数据上传失败 \033[0m"

        echo        

        }
        mkdir -p /var/Send/$data/
        $@  &> /var/Send/$data/${2}.log
        cat /var/Send/$data/${2}.log |grep -E 'error|失败' > /var/Send/$data/${1}_error.log
        echo "${2}" >> ./develop.log
}       

#热更
function Hot_update {

        function gatfile {
		#目录更新
        $ssh $1 "tar -zxf ${dir}bzsch5_server.tar.gz -C ${gamedir}${3}_${2}/server/" > /dev/null
        [ $? -eq 0 ] && echo -e "\033[32m ${3}_${2} 更新成功 \033[0m" || echo -e "\033[31m ${3}_${2} 更新失败 \033[0m"
        
        #主库执行sql
        $ssh $1 "if [ -f ${gamedir}${3}_${2}/server/sql/update.sql ];then $sshmysql bzsch5_${3}_${2} < ${gamedir}${3}_${2}/server/sql/update.sql && [ $? -eq 0 ] && echo -e \"\033[32m ${3}_${2} 更新主库成功 \033[0m\" || echo -e \"\033[31m ${3}_${2} 更新主库失败 \033[0m\"; else echo -e '\033[33m sql不用更新\033[0m'; fi"

        #热更
        $ssh $1 "cd ${gamedir}${3}_${2}/server/script && sh rel.sh hot"

        } 
        mkdir -p /var/Hot/$data/
        $@  &> /var/Hot/$data/${4}_${3}.log
        cat /var/Hot/$data/${4}_${3}.log |grep -E 'error|失败' > /var/Hot/$data/${4}_${3}_error.log
	    echo "${4}_${3}" >> ./develop.log
}


#更新游戏
function game_update {

        function gatfile {
        #目录更新
        $ssh $1 "tar -zxvf ${dir}bzsch5_server.tar.gz -C ${gamedir}${3}_${2}/server/" 
        [ $? -eq 0 ] && echo -e "\033[32m ${3}_${2} 更新成功 \033[0m" || echo -e "\033[31m ${3}_${2} 更新失败 \033[0m"

        #主库执行sql
        $ssh $1 "if [ -f ${gamedir}${3}_${2}/server/sql/update.sql ];then $sshmysql bzsch5_${3}_${2} < ${gamedir}${3}_${2}/server/sql/update.sql && [ $? -eq 0 ] && echo -e \"\033[32m ${3}_${2} 更新主库成功 \033[0m\" || echo -e \"\033[31m ${3}_${2} 更新主库失败 \033[0m\"; else echo -e '\033[33m sql不用更新\033[0m'; fi"
    

        }
        mkdir -p /var/Update/$data/
        $@  &> /var/Update/$data/${4}_${3}.log
        cat /var/Update/$data/${4}_${3}.log |grep -E 'error|失败' > /var/Update/$data/${4}_${3}_error.log
        echo "${4}_${3}" >> ./develop.log
}



#批量关游戏
function stop_game {

	function gatfile {
		echo "$3_$2 start_time : `date \"+%Y-%m-%d %H:%M:%S\"`" >> ./time.log
		process=`echo "$3_$2"|sed 's/_s/_/g;s/$/_/g'`
		$ssh $1 "cd $gamedir/${3}_${2}/server/script;sh rel.sh stop" &> /var/stop/$data/${3}_${2}.log
		sleep 10
		result=`$ssh $1 "ps aux | grep $process|grep -v grep|wc -l"`
		if [ $result -ne 0 ];then
			echo -e "\033[33m ${3}_${2} 游戏进程还没关闭,现在进行kill操作 \033[0m" &> /dev/null
			$ssh $1 "ps aux | grep $process | grep -v 'grep'|awk '{print \$2}'|xargs kill -15 "
		fi
                cat /var/stop/$data/${3}_${2}.log |grep 'error' > /var/stop/$data/${3}_${2}_error.log
                echo "${3}_${2}" >> ./develop.log
		echo "$3_$2 stop_time : `date \"+%Y-%m-%d %H:%M:%S\"`" >> ./time.log
	}
	mkdir -p /var/stop/$data/
	$@
}
#批量开游戏
function start_game {
        function gatfile {
                $ssh $1 "cd $gamedir/${3}_${2}/server/script;sh rel.sh start" &> /var/start/$data/${3}_${2}.log
                cat /var/start/$data/${3}_${2}.log |grep 'error' > /var/start/$data/${3}_${2}_error.log
                echo "${3}_${2}" >> ./develop.log
        }
	mkdir -p /var/start/$data/
        $@
}

#检查游戏是否关闭
function check_game {
        function gatfile {
		      process=`echo "$3_$2"|sed 's/$/_/g'`
                result=`$ssh $1 "ps aux | grep ${process} | grep -v grep|wc -l"`
		if [ $result -ne 0 ];then
			echo -e "\033[32m ${3}_${2} 游戏开启 \033[0m"
			$ssh $1 "ps aux | grep ${process}| grep -v 'grep' |awk '{print \$2}' |xargs kill -15"
		else
			echo -e "\033[31m ${3}_${2} 游戏关闭 \033[0m"
		fi
        }
        $@
}


function processlist {
	[ -z ${2} ] && echo -e "\033[33m 用法: sh menu.sh $1  gatfile.sh(列表) \033[0m" && exit 1
	if [ $1 == "plush_file" ];then
		 cat ./$2| sed 's/"//g'|awk '{print $1" "$2}'|sort|uniq > ./tmp_${2}
       		 if [ -s ./tmp_${2} ];then
                    
                    #安全起见，dir不为空
                    if [ -z $dir ];then
                        echo "\033[33mdir 为空\033[0m"
                        exit
                    fi
                    #创建目录
                    $ssh $stable_ip "mkdir -p /tmp/update_bzsch5/$nowtime&&rm /tmp/update_bzsch5/$nowtime/* -rf"
                    [ $? -eq 0 ] && echo -e "\033[32m 源目录创建成功 \033[0m" || (echo -e "\033[33m 源目录创建失败 \033[0m";exit)
                    
                    #压缩更新目录，不保存目录结构
                    $ssh $stable_ip "cd  /tmp/update_bzsch5/$nowtime/&&tar -zcf bzsch5_server.tar.gz -C ${gamedir}${src_agent_id}/server/ {ebin,deps,sql}"
                    [ $? -eq 0 ] && (echo -e "\033[32m 源目录压缩成功 \033[0m";echo -e  "\033[35m 目录:/tmp/update_bzsch5/$nowtime/bzsch5_server.tar.gz \033[0m") || (echo -e "\033[33m 源目录压缩失败 \033[0m";exit)
                    
                    
                     filename=tmp_$2
       		         thread=5

       		 else
       		         echo -e "\033[33m sh menu.sh $1  gatfile.sh(列表) \033[0m" && exit 1
       		 fi	

	else
        	if [ -s ./${2} ];then
			        filename=$2
                    sed -i '/^$/d' ./$filename
        	        thread=1
            else
                echo -e "\033[33m sh menu.sh $1  gatfile.sh(列表) \033[0m" && exit 1
            fi
    fi
        	        tmp_fifofile="./$$.fifo"
        	        mkfifo $tmp_fifofile      # 新建一个fifo类型的文件
        	        exec 6<>$tmp_fifofile      # 将fd6指向fifo类型
        	        /bin/rm $tmp_fifofile

        	        for ((i=0;i<$thread;i++));do
        	                echo -e "\n" >&6
        	        done

        	        exec 5<$filename
        	        while read line <&5
        	        do
        	                excute_line=`echo $line|sed 's/"//g'`
        	                read -u6
                {
        	                $1 $excute_line
        	                echo >&6
				} &
        	        done

}


#进度条
function the_plan {
        [ "$2" == "" ] && exit
	    implement=`cat ./implement.log`
        [ "$implement" == "no" ] && exit
        dir=`echo $1|awk -F'_' '{print $1}'`
        if [ "$1" == "plush_file" ];then
            filename=tmp_$2
        else
             filename=$2
            
        fi
        all_nums=`cat $filename|wc -l`
        nums=0
        on=0
        while true
        do
                if [ $all_nums -eq 0 ];then
                        break
                else
                        if [ $nums -ne $all_nums ];then
                                complete_num=`cat ./develop.log|wc -l`
                                if [ $nums -eq $complete_num -a $nums -eq 0 ];then
                                        [ $on -eq 0 ]&&echo -e "\033[32m[-----------------------------------------0%---"$nums/$all_nums"]\033[0m"
                                        on=1
                                        continue
                                elif [ $nums -lt $complete_num ];then
                                        let nums=$nums+1
                                        Percentage=`expr $nums/${all_nums}|bc -l|cut -c 2,3`%
                                        [ $nums -eq ${all_nums} ] && Percentage="100%"
                                        ser_agent=`cat ./develop.log|awk 'NR=='''$nums'''{print}'`
wait
                                        if [ ! -s /var/$dir/$data/${ser_agent}_error.log ];then
                                                echo -e "\033[32m[-------------------$ser_agent success----------------------$Percentage---"$nums/$all_nums"]\033[0m"
                                        else
                                                echo -e "\033[31m[-------------------$ser_agent false----------------------$Percentage---"$nums/$all_nums"]\033[0m"
                                        fi
                                        continue
                                else
                                        continue
                                fi
                        else
                                break
                        fi
                fi
                sleep 2
        done

}

the_plan $1 $2 &

case $1 in
	game_install) $@ ;;
	update_time) $@ ;;
	look_log_content) $@ ;;
	truncate_game) $@ ;;
	Hot_update) processlist $@ ;;
	stop_game) processlist $@ ;;
	start_game) processlist $@ ;;
	check_game) processlist $@ ;;
	plush_file) processlist $@ ;;
	game_update) processlist $@ ;;
	*) menu ;;
esac
wait
